<template>
  <div>
    <el-dialog
      :model-value="props.dialogVisible"
      title="修改密码"
      width="400px"
      :close-on-click-modal="false"
      :before-close="handleClose">
      <el-form ref="pwdFormRef" :model="pwdForm" :rules="pwdFormRules" label-width="100px" @submit.prevent>
        <el-form-item label="新密码：" prop="newPwd">
          <el-input v-model="pwdForm.newPwd" type="password" show-password placeholder="请输入新密码" clearable/>
        </el-form-item>
        <el-form-item label="确认密码：" prop="confirmPwd">
          <el-input v-model="pwdForm.confirmPwd" type="password" show-password placeholder="请输入确认密码" clearable/>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="handleSubmit(pwdFormRef)">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="ModifyPasswordForm">
import { ref, reactive, watch, ComponentInternalInstance, getCurrentInstance } from 'vue'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { passwordUpdate } from '@/api/auth'
import { Md5 } from 'ts-md5'
import rsa from '@/utils/rsa'

const { proxy } = getCurrentInstance() as ComponentInternalInstance

const props = defineProps({
  dialogVisible: {
    type: Boolean,
    default: false
  }
})

const router = useRouter()
const store = useStore()
const pwdForm = reactive({
  newPwd: '',
  confirmPwd: ''
})
const pwdFormRef = ref<FormInstance>()
const pwdFormRules = reactive<FormRules>({
  newPwd: [
    { required: true, message: '请输入密码！' }
  ],
  confirmPwd: [
    { required: true, message: '请输入确认密码！' },
    {
      validator: (rules, value, callback) => {
        if (value) {
          if (value === pwdForm.newPwd) {
            callback()
          } else {
            callback(new Error('和新密码不一致！'))
          }
        } else {
          callback(new Error('请输入确认密码！'))
        }
      }
    }
  ]
})

// 提交表单
const handleSubmit = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async (valid, fields) => {
    if (valid) {
      let rr = new rsa()
      let params = {
        userId: store.state.user.userInfoStore.userId,
        pwd:rr.rsaEncrypt(pwdForm.newPwd)
      }
      await passwordUpdate(params).then((res: any) => {
        if (res.code === 0) {
          ElMessage.success(`修改密码成功，请重新登录系统。`)
          handleClose()
          sessionStorage.removeItem('loginUserInfo')
          router.push({
            path: '/login',
            replace: true
          })
        } else {
          ElMessage.error(`${res.msg}`)
        }
      }).catch(err => {
        console.log(err)
        ElMessage.error(`接口错误，状态码为 ${err.response.status}。`)
      })
    }
  })
}

// 重置表单
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

// 关闭弹窗
const handleClose = () => {
  resetForm(pwdFormRef.value)
  proxy?.$emit('update:dialogVisible', false)
}
</script>

<style lang="stylus" scoped>

</style>
